/*=========================================================================

  Library:   CTK

  Copyright (c) Kitware Inc.

  Licensed under the Apache License, Version 2.0 (the "License");
  you may not use this file except in compliance with the License.
  You may obtain a copy of the License at

      http://commontk.org/LICENSE

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.

=========================================================================*/

// Qt includes
#include <QDir>
#if (QT_VERSION >= QT_VERSION_CHECK(5, 0, 0))
#include <QTemporaryDir>
#endif
#include <QTextStream>

// CTK includes
#include "ctkCoreTestingMacros.h"
#include "ctkUtils.h"

// STD includes
#include <cstdlib>


//-----------------------------------------------------------------------------
int ctkUtilsIsDirEmptyTest1(int argc, char * argv [] )
{
  Q_UNUSED(argc);
  Q_UNUSED(argv);

#if (QT_VERSION >= QT_VERSION_CHECK(5, 0, 0))
   QTemporaryDir tempDir;
   CHECK_BOOL(tempDir.isValid(), true);
#else
   QDir tmp = QDir::temp();
   QString temporaryDirName =
       QString("ctkUtilsIsDirEmptyTest1.%1").arg(QTime::currentTime().toString("hhmmsszzz"));
   tmp.mkdir(temporaryDirName);
   bool isValid = tmp.cd(temporaryDirName);
   CHECK_BOOL(isValid, true);
   QDir tempDir = QDir(tmp.absolutePath());
#endif

#if (QT_VERSION >= QT_VERSION_CHECK(5, 2, 0))
   CHECK_BOOL(QFileInfo::exists(tempDir.path()), true);
#else
   CHECK_BOOL(QFileInfo(tempDir.path()).exists(), true);
#endif

   CHECK_BOOL(ctk::isDirEmpty(QDir(tempDir.path())), true);

   // Create file
   QString filePath = tempDir.filePath("file.txt");
   QFile file(filePath);
   file.open(QIODevice::Text | QIODevice::WriteOnly);
   QTextStream out(&file);
   out << "Generated by ctkUtilsIsDirEmptyTest1" << ctk::endl;
   file.close();

   CHECK_BOOL(QFile::exists(filePath), true);

   CHECK_BOOL(ctk::isDirEmpty(QDir(tempDir.path())), false);

#if (QT_VERSION >= QT_VERSION_CHECK(5, 0, 0))
  // QTemporaryDir is automatically deleted
#else
  ctk::removeDirRecursively(tempDir.path());
#endif
  return EXIT_SUCCESS;
}
